$(function () {
    init_mudal();
    init_grade();
});

/**初始化模板**/
function init_mudal() {
    /**初始化部门树状图**/
    $.post(ctx+"dept/getDeptToJSTree",{},function (r) {
        var array  = r.msg;
        $("#deptjsTree_jsonG").jstree({
            "core": {"multiple": true,"data":array},
            "checkbox" : {"keep_selected_style" : false},
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#deptjsTree_jsonG').on("changed.jstree", function (e, data) {
            var exConfigUuid = $("#exConfig_form_idG").val();
            //if (exConfigUuid == "" || exConfigUuid == undefined){$JuXue.n_danger("请选择左侧得意向项目");return ;}
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;
            if (action == "deselect_node"){
                $("#deptG"+nodeid).remove();}else{
                var  divapent = '<div class="input-group col-md-10 col-sm-10 m-8" id="deptG'+nodeid+'" cuid ="1" data-id="'+nodeid+'">\n' +
                    '<span class="input-group-addon cursor" deptid="'+nodeid+'">'+text+'</span>' +
                    '<span class="input-group-addon"><a href="#" onclick="downMoveG(this)"><i class="fa fa-arrow-circle-down"></i></a></span>' +
                    '<span class="input-group-addon"><a href="#" onclick="upMoveG(this)"><i class="fa fa-arrow-circle-up"></i></a></span>' +
                    '</div>';
                $("#exConfig_formG").append(divapent);
            }
        });
    });

    sessionStorage.setItem("selectDept","");
    sessionStorage.setItem("selectInternG","");
}

function init_grade() {
    $("#grad_form").find('input').each(function (index,val) {
        $(this).val('');
    });

    $.getJSON(ctx+"grade/list",{},function (r) {
        var data = r.data;
        var nobr = '';
        $("#grad_form").empty();
        $.each(data,function (index,val) {
            var id = val.gId;
            var name = val.gName;
            nobr = '<div class="input-group col-md-11 col-sm-11 m-6" >' +
                '<span class="input-group-addon">'+name+'</span>' +
                '<input type="number" class="form-control" id="'+id+'" placeholder="填写等级数字"/></div>';
            $("#grad_form").append(nobr);
        });
    })
}

function chooseFenG(btn) {
    $.post(ctx+"cRound/getAllRound",{"rType":btn},function (r) {
        if (r.code === 0){
            var alldata = r.data;$("#exaddG").empty();
            $.each(alldata,function (index,val) {
                $("#exaddG").append("<div class='fc-event'><a onclick='selectInternG(this);' type='"+btn+"' data-id="+val.rUuid+" >"+val.rName+" </a> " +
                    "<a onclick='exdeleteG(this);' data-id="+val.rId+"><i class='fa fa-trash-o pull-right'></i></a></div>");
            });
        }else{$JuXue.n_success(r.msg);}
    });
}

function chooseTuiG(btn) {
    $.post(ctx+"cRound/getAllRound",{"rType":btn},function (r) {
        if (r.code === 0){
            var alldata = r.data;$("#InterConfigG").empty();
            $.each(alldata,function (index,val) {
                $("#InterConfigG").append("<div class='fc-event'><a onclick='selectInternForDingG(this);' type='"+btn+"' data-id="+val.rUuid+" >"+val.rName+" </a> " +
                    "</div>");
            });
        }else{$JuXue.n_success(r.msg);}
    });
}

function selectInternForDingG(btn){
    $("#InterConfigG").find("div").each(function () {
        $(this).removeClass("bg-blue-1");
    });
    $(btn).parent().addClass("bg-blue-1");
    var text = $(btn).text();
    var uuid = $(btn).attr('data-id');
    sessionStorage.setItem("selectInternG",text);
    sessionStorage.setItem("selectInternGid",uuid);

    $.post(ctx+"cRound/getRoundConfig",{cPid:uuid,cType:"1"},function (r) {
        var data = r.data.config;
        init_InterDept(data);
    })
}

function init_InterDept(array) {
    $("#deptListExtG").empty();
    $.each(array,function (index,val) {
        $("#deptListExtG").append('<div class="fc-event ui-draggable" ><a href="#" onclick="selectDeptExG(this)" data="'+val.cDeptid+'">'+val.cDeptName+'</a></div>');
    });
}

function selectDeptExG(btn) {
    var selectInter = sessionStorage.getItem("selectInternGid");
    if (selectInter === ""){$JuXue.n_danger("请选择项目");return }
    $("#deptListExtG").find("div").each(function () {$(this).removeClass("bg-blue-1");});
    $(btn).parent().addClass("bg-blue-1");
    var deptid = $(btn).attr("data");
    sessionStorage.setItem("selectInternDeptid",deptid);
    var type = sessionStorage.getItem("clickTabTuiG");
    /**加载部门的信息**/
    $.getJSON(ctx+"dept/getDeptAndUserByCRound",{cPid: selectInter,deptid:deptid,cType:type},function (res) {
        if (res.code === 0){
            var data = res.data;
            $("#userDingjsTree_jsonG").jstree("destroy");
            $("#userDingjsTree_jsonG").jstree({
                "core": {"multiple": true,"data":data},
                "checkbox" : {"keep_selected_style" : false},
                "plugins" : [ "wholerow", "checkbox" ]
            });
        }else{$JuXue.n_danger("获取部门人员失败");}
    });
}

function saveInternDingG(){
    var selectInternDeptid = sessionStorage.getItem("selectInternDeptid");
    if (selectInternDeptid === ""){$JuXue.n_danger("请选择部门");return }
    var selectInter = sessionStorage.getItem("selectInternGid");
    if (selectInter === ""){$JuXue.n_danger("请选择项目");return }
    var data = $("#userDingjsTree_jsonG").jstree().get_selected(false);
    if (data.length <= 0){$JuXue.n_danger("请选择人员"); return;}

    var users = data.join(",");
    var type = sessionStorage.getItem("clickTabTuiG");
    $.post(ctx+"cRoundLevel/addNewLevel",{lUuid:selectInter,lDeptid:selectInternDeptid,lIntPerson:users,lType:type},function (res) {
        if (res.code === 0){$JuXue.n_success("设置成功");
        }else{$JuXue.n_danger("设置失败");
        }
    });
}

/**删除**/
function exdeleteG(btn) {
    var data_select = $(btn).attr("data-id");
    if (data_select !== "" && data_select !== undefined){
        $JuXue.confirm({
            text: "确定删除选中模板？",
            confirmButtonText: "确定删除"
        }, function() {
            $.post(ctx + 'cRound/deleteRound', { "rId": data_select }, function(r) {
                if (r.code === 0) {
                    $JuXue.n_success(r.msg);
                    $(btn).parent().remove();
                    $("#exConfig_formG").empty();
                    $("#grad_form").find('input').each(function (index,val) {
                        $(this).val('');
                    });
                    $("#deptjsTree_jsonG").jstree('uncheck_all');
                } else {$JuXue.n_danger(r.msg);}
            });
        });
    }
}

/**查询所有得信息**/
function selectInternG(btn) {
    var text = $(btn).text();
    sessionStorage.setItem("selectInternG",text);
    var type = $(btn).attr("type");
    $("#exaddG").find("div").each(function () {$(this).removeClass("bg-blue-1");});
    $(btn).parent().addClass("bg-blue-1");
    var data_select = $(btn).attr("data-id");
    $("#deptjsTree_jsonG").jstree().deselect_all(true);
    $("#exConfig_formG").empty();
    sessionStorage.setItem("refreshId",data_select);
    sessionStorage.setItem("refreshType",type);
    if (data_select !== "" && data_select !== undefined){
        $.post(ctx+"cRound/getRoundConfig",{cPid:data_select,cType:type},function (r) {
            if (r.code === 0){
                $("#grad_form").find('input').each(function (index,val) {
                    $(this).val('');
                });
                $("#exConfig_form_idG").val(data_select);
                var data = r.data.config;
                var deptid = new Array();
                $.each(data,function (index,val) {
                    deptid.push(val.cDeptid);
                    var  divapent = '<div class="input-group col-md-10 col-sm-10 m-8" id="deptG'+val.cDeptid+'" cuid ="'+val.cUuid+'" data-id="'+val.cDeptid+'">\n' +
                        '<span class="input-group-addon cursor" deptid="'+val.cDeptid+'">'+val.cDeptName+'</span>' +
                        '<span class="input-group-addon "><a href="#" onclick="downMoveG(this)"><i class="fa fa-arrow-circle-down"></i></a></span>' +
                        '<span class="input-group-addon"><a href="#" onclick="upMoveG(this)" ><i class="fa fa-arrow-circle-up"></i></a></span>'+
                        '</div>';
                    $("#exConfig_formG").append(divapent);
                });
                $("#deptjsTree_jsonG").jstree().select_node(deptid,true,true);

                var grade = r.data.grade;
                $.each(grade,function (index,val) {
                    var gUuid = val.cGradeId;
                    var gCount = val.cCount;
                    $("#grad_form").find('input').each(function (index,val) {
                        if(gUuid===$(this).attr("id")){
                            $(this).val(gCount);
                        }
                    })
                })
            }else{
                $JuXue.n_danger("加载数据失败");
            }
        });
    }
}

/**新增**/
function selectInternAddG(btn) {
    var data_select = $(btn).attr("data-click");
    var type = sessionStorage.getItem("clickTabFenG");
    if (data_select != "" && data_select != undefined){
        $.post(ctx+"cRound/addNewRound",{rName:data_select,rType:type},function (r) {
            if (r.code == 0){
                $JuXue.n_success("新增成功");
                $("#exaddG").append("<div class='fc-event'><a onclick='selectInternG(this);' type='"+type+"' data-id="+r.data.rUuid+" >"+data_select+" </a> " +
                    "<a onclick='exdeleteG(this);' data-id="+r.data.rId+"><i class='fa fa-trash-o pull-right'></i></a></div>");
            }else{$JuXue.n_danger(r.msg);}
        });
    }
}


/**推广模板得下移**/
function downMoveG(btn) {
    var $div = $(btn).parent().parent();
    var lent = $div.next().length;
    if (lent === 0){$JuXue.n_danger("不能下移");return ;}
    //下移
    //1: 获取本节点所有得信息
    var divInfo = $div.html();
    //2：获取部门和部门id
    var nodeid = $div.attr("id");
    var deptid = $div.attr("data-id");
    var cuid = $div.attr("cuid");
    //3: 找到下一级 得下一级兄弟，并且删除 本节点
    /**获取inputnum得值**/
    var inputvaluenum = $(btn).parent().prev().val();
    /**获取数量总额**/
    var inputValueTotle = $(btn).parent().parent().children('input').eq(1).val();

    var sub$div = $div.next();
    //4: 新建一个节点  追加到下一级
    var  divapent = '<div class="input-group col-md-10 col-sm-10 m-8" id="'+nodeid+'" cuid="'+cuid+'" data-id="'+deptid+'"></div>';
    $div.remove();
    sub$div.after(divapent);
    $("#"+nodeid).append(divInfo);
    //追加节点
    $("#"+nodeid).children('input').eq(0).val(inputvaluenum);
    $("#"+nodeid).children('input').eq(1).val(inputValueTotle);
}
/**推广模板得上移动**/
function upMoveG(btn) {
    var $div = $(btn).parent().parent();
    var lent = $div.prev().length;
    if (lent === 0){$JuXue.n_danger("不能上移");return ;}
    //上移
    //1: 获取本节点所有得信息
    var divInfo = $div.html();
    //2：获取部门和部门id
    var nodeid = $div.attr("id");
    var deptid = $div.attr("data-id");
    var cuid = $div.attr("cuid");
    //3: 找到上一级 得上一级兄弟，并且删除 本节点
    /**获取input得值**/
    var inputvalue = $(btn).parent().prev().prev().val();
    /**获取数量总额**/
    var inputValueTotle = $(btn).parent().parent().children('input').eq(1).val();
    var sub$div = $div.prev();
    //4: 新建一个节点  追加到上一级
    var  divapent = '<div class="input-group col-md-10 col-sm-10 m-8" id="'+nodeid+'" cuid="'+cuid+'" data-id="'+deptid+'"></div>';
    $div.remove();
    sub$div.before(divapent);
    $("#"+nodeid).append(divInfo);
    //追加节点
    $("#"+nodeid).children('input').eq(0).val(inputvalue);
    $("#"+nodeid).children('input').eq(1).val(inputValueTotle);
}


/**保存**/
function saveExConfigG() {
    //1: 获取更新得项目
    var exConfigUuid = $("#exConfig_form_idG").val();
    if (exConfigUuid == "" || exConfigUuid == undefined){$JuXue.n_danger("请选择左侧得意向项目");return ;}
    //需要得数据{部门id, 配置数目，排序，新老数据得区别}
    var deptids = new Array();
    var cuids = new Array();
    var orders = new Array();

    $("#exConfig_formG").find("div").each(function (index,val) {
        var deptid = $(this).attr("data-id");
        deptids.push(deptid);
        var cuid = $(this).attr("cuid");
        cuids.push(cuid);
        orders.push(index+1);
    });
    var nums = new Array();
    var totle = new Array();
    $("#grad_form").find("input").each(function (index,val) {
        var gradeid = $(this).attr("id");
        totle.push(gradeid);
        var cuid = $(this).val();
        nums.push(cuid);
    });
    var gradenum = nums.join(",");
    var grade = totle.join(",");
    var deptidsstr = deptids.join(",");
    var cuidsstr = cuids.join(",");
    var ordersstr = orders.join(",");
    if (deptidsstr == "" || deptidsstr == undefined){$JuXue.n_danger("请选择部门");return ;}
    var type = sessionStorage.getItem("clickTabFenG");
    $.post(ctx+"cRoundConfig/editRoundConfig",{gCount:gradenum,gUuid:grade,
        cUuid:cuidsstr,cOrder:ordersstr,cPid:exConfigUuid,cDeptid:deptidsstr,cType:type},function (r) {
        if (r.code == 0){$JuXue.n_success("保存成功");
            var data_select = sessionStorage.getItem("refreshId");
            var type = sessionStorage.getItem("refreshType");
            $("#deptjsTree_jsonG").jstree().deselect_all(true);
            $("#exConfig_formG").empty();
            $.post(ctx+"cRound/getRoundConfig",{cPid:data_select,cType:type},function (r) {
                if (r.code === 0){
                    $("#grad_form").find('input').each(function (index,val) {
                        $(this).val('');
                    });
                    $("#exConfig_form_idG").val(data_select);
                    var data = r.data.config;
                    var deptid = new Array();
                    $.each(data,function (index,val) {
                        deptid.push(val.cDeptid);
                        var  divapent = '<div class="input-group col-md-10 col-sm-10 m-8" id="deptG'+val.cDeptid+'" cuid ="'+val.cUuid+'" data-id="'+val.cDeptid+'">\n' +
                            '<span class="input-group-addon cursor" deptid="'+val.cDeptid+'">'+val.cDeptName+'</span>' +
                            '<span class="input-group-addon "><a href="#" onclick="downMoveG(this)"><i class="fa fa-arrow-circle-down"></i></a></span>' +
                            '<span class="input-group-addon"><a href="#" onclick="upMoveG(this)" ><i class="fa fa-arrow-circle-up"></i></a></span>'+
                            '</div>';
                        $("#exConfig_formG").append(divapent);
                    });
                    $("#deptjsTree_jsonG").jstree().select_node(deptid,true,true);

                    var grade = r.data.grade;
                    $.each(grade,function (index,val) {
                        var gUuid = val.cGradeId;
                        var gCount = val.cCount;
                        $("#grad_form").find('input').each(function (index,val) {
                            if(gUuid===$(this).attr("id")){
                                $(this).val(gCount);
                            }
                        })
                    })
                }else{
                    $JuXue.n_danger("加载数据失败");
                }
            });
        }else{$JuXue.n_danger(r.msg)}
    });
}


